"""
Examples of using the simplified event configuration system.

This file demonstrates the new, clean interface for event configuration.
"""

from learners.events.config import configure_events


def example_template_usage():
    """Examples of using predefined templates."""
    print("=== Template Usage Examples ===")

    # 1. Minimal setup (events enabled, no handlers)
    config = configure_events(template="minimal")
    print(f"Minimal config: {len(config.handlers)} handlers")

    # 2. Basic logging
    config = configure_events(template="basic")
    print(f"Basic config: {len(config.handlers)} handlers")

    # 3. Continual learning optimized
    config = configure_events(template="continual")
    print(f"Continual config: {len(config.handlers)} handlers")

    # 4. Research mode with detailed monitoring
    config = configure_events(template="research")
    print(f"Research config: {len(config.handlers)} handlers")

    # 5. Debug mode with verbose logging
    config = configure_events(template="debug")
    print(f"Debug config: {len(config.handlers)} handlers")


def example_template_with_overrides():
    """Examples of templates with custom overrides."""
    print("\n=== Template with Overrides ===")

    # Override emission interval and logging
    config = configure_events(
        template="continual", log_events=True
    )

    print(f"Logging enabled: {config.log_events}")
    print(f"Handlers: {[h.type for h in config.handlers]}")


def example_programmatic_configuration():
    """Examples of creating configuration programmatically."""
    print("\n=== Programmatic Configuration ===")

    # Start with minimal config and add handlers
    config = configure_events(template="minimal")

    # Add custom handlers
    config.add_handler(
        handler_type="LoggingHandler",
        events=["ON_TASK_START", "ON_TASK_END"],
        config={"log_level": "INFO"},
    )

    config.add_handler(
        handler_type="MetricsHandler",
        events=["ON_TRAIN_EPOCH_END"],
        config={"save_to_file": True},
    )

    print(f"Custom config: {[h.type for h in config.handlers]}")


def example_file_configuration():
    """Examples of loading from configuration files."""
    print("\n=== File Configuration ===")

    # Create a sample YAML config
    yaml_content = """
events:
  enabled: true
  log_events: true

  handlers:
    - type: "LoggingHandler"
      events: ["ON_TASK_START", "ON_TASK_END"]
      config:
        log_level: "INFO"
      enabled: true

    - type: "CustomHandler"
      events: ["ON_TRAIN_EPOCH_END"]
      config:
        custom_param: "value"
      enabled: true
"""

    # Save to temporary file
    import tempfile

    with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as f:
        f.write(yaml_content)
        temp_path = f.name

    try:
        # Load from YAML file
        config = configure_events(config_file=temp_path)
        print(f"Loaded from YAML: {len(config.handlers)} handlers")
        print(f"Handler types: {[h.type for h in config.handlers]}")
    except ImportError:
        print("PyYAML not available, skipping YAML example")
    finally:
        import os

        if os.path.exists(temp_path):
            os.unlink(temp_path)


def example_environment_overrides():
    """Examples of environment variable overrides."""
    print("\n=== Environment Variable Overrides ===")

    import os

    # Set environment variables
    os.environ["EVENT_ENABLED"] = "true"
    os.environ["EVENT_LOG_EVENTS"] = "true"

    # Load config (environment variables are applied automatically)
    config = configure_events(template="basic")

    print("Environment overrides applied:")
    print(f"  Enabled: {config.enabled}")
    print(f"  Log events: {config.log_events}")

    # Clean up
    for key in ["EVENT_ENABLED", "EVENT_LOG_EVENTS"]:
        os.environ.pop(key, None)


def example_learner_integration():
    """Example of integrating with a learner."""
    print("\n=== Learner Integration ===")

    # Configure events
    config = configure_events(template="continual")

    # Convert to format suitable for learner arguments
    event_args = config.to_args_dict()

    print("Arguments for learner:")
    for key, value in event_args.items():
        if key != "event_config":  # Skip the nested dict for cleaner output
            print(f"  {key}: {value}")

    # This is how you would use it in practice:
    # learner_args.update(event_args)
    # learner = SomeLearner(**learner_args)


def example_save_and_load():
    """Example of saving and loading configurations."""
    print("\n=== Save and Load ===")

    # Create a custom configuration
    config = configure_events(template="continual")
    config.log_events = True

    # Save to file
    import tempfile
    import os

    with tempfile.TemporaryDirectory() as temp_dir:
        # Save as JSON
        json_path = os.path.join(temp_dir, "config.json")
        config.save_json(json_path)
        print(f"Saved to JSON: {json_path}")

        # Load from JSON
        loaded_config = configure_events(config_file=json_path)
        print(f"Loaded  : {loaded_config}")

        try:
            # Save as YAML
            yaml_path = os.path.join(temp_dir, "config.yaml")
            config.save_yaml(yaml_path)
            print(f"Saved to YAML: {yaml_path}")

            # Load from YAML
            loaded_yaml_config = configure_events(config_file=yaml_path)
            print(f"YAML  : {loaded_yaml_config}")
        except ImportError:
            print("PyYAML not available, skipping YAML save/load")


if __name__ == "__main__":
    """Run all examples."""
    print("Event Configuration System Examples")
    print("=" * 60)

    example_template_usage()
    example_template_with_overrides()
    example_programmatic_configuration()
    example_file_configuration()
    example_environment_overrides()
    example_learner_integration()
    example_save_and_load()

    print("\n" + "=" * 60)
    print("All examples completed successfully!")
    print(
        "\nKey takeaway: One simple function 'configure_events()' handles all use cases!"
    )
